package com.shopping.cart

import grails.test.ControllerUnitTestCase
import org.springframework.mock.web.MockMultipartFile
import org.springframework.web.multipart.MultipartFile
import org.codehaus.groovy.grails.commons.ConfigurationHolder


class ImageControllerTests extends ControllerUnitTestCase {

    ImageController controller

    void setUp() {
        super.setUp()
        controller = new ImageController()
        mockDomain(Item)
        ConfigurationHolder.config = [:]
        ConfigurationHolder.config.'uploadFiles.directory' = 'test'
    }

    void testNoImagesPassedInDoesNotSaveThem() {
        ItemCategory category = new ItemCategory()
        Item item = new Item()
        mockDomain(Item, [item])
        mockDomain(ItemCategory, [category])
        mockCommandObject(UploadCommand)

        UploadCommand command = new UploadCommand()
        command.category = category
        command.item = item
        controller.upload command
        assertEquals 'minSize', renderArgs.model.cmd.errors.images
        assertEquals 'uploadForm', renderArgs.view
        assertNull mockFlash.message
    }

    void testImagePassedInCreatesImages() {
        Item item = new Item(title: 'yo', amount: 1.1)
        ItemCategory category = new ItemCategory(category:'cats are cool')
        mockDomain(Item, [item])
        mockDomain(ItemCategory, [category])
        mockCommandObject(UploadCommand)

        UploadCommand command = new UploadCommand()
        command.category = category
        command.item = item

        MultipartFile.metaClass.transferTo = {File file ->
            assertEquals 'name', file.getName()
        }

        byte[] content = ['a', 'b']
        command.images = [new MockMultipartFile("name", 'originalName', 'contenttype', content)]

        item.addToCategories category
        command.item = item
        controller.upload command

        assertFalse renderArgs.model.cmd.hasErrors()
        assertFalse renderArgs.model.cmd.item.hasErrors()
        assertFalse renderArgs.model.cmd.category.hasErrors()
        assertEquals 'uploadForm', renderArgs.view
        assertEquals 'Item has been successfully added', mockFlash.message
    }
}
